<script lang="tsx">
import { computed, defineComponent, unref, PropType } from 'vue'
import { ElMenu, ElScrollbar } from 'element-plus'
import { useAppStore } from '@/store/modules/app'
import { useMenuStore } from '@/store/modules/menu'
import { useRouter } from 'vue-router'
import { useRenderMenuItem } from './components/useRenderMenuItem'
import { useDesign } from '@/hooks/web/useDesign'

const { getPrefixCls } = useDesign()

const prefixCls = getPrefixCls('menu')

// 定义菜单项接口，不依赖路由
export interface MenuItem {
  id: string | number
  title: string
  icon?: string
  path?: string
  url?: string
  children?: MenuItem[]
  disabled?: boolean
  hidden?: boolean
  [key: string]: any // 支持其他自定义属性
}

export default defineComponent({
  name: 'Menu',
  props: {
    // 菜单数据
    menuData: {
      type: Array as PropType<MenuItem[]>,
      required: false,
      default: () => []
    },
    // 当前激活的菜单项
    activeKey: {
      type: String,
      default: ''
    },
    // 菜单选择回调
    onMenuSelect: {
      type: Function as PropType<(item: MenuItem, index: string) => void>,
      default: undefined
    },
    // 菜单模式
    mode: {
      type: String as PropType<'vertical' | 'horizontal'>,
      default: 'vertical'
    },
    // 是否折叠
    collapse: {
      type: Boolean,
      default: false
    },
    // 是否只展开一个子菜单
    uniqueOpened: {
      type: Boolean,
      default: true
    }
  },
  emits: ['menu-select'],
  setup(props, { emit }) {
    const appStore = useAppStore()
    const menuStore = useMenuStore()
    const router = useRouter()

    const layout = computed(() => appStore.getLayout)

    // 计算菜单数据，优先使用props，否则从store获取
    const menuData = computed(() => {
      if (props.menuData && props.menuData.length > 0) {
        return props.menuData
      }
      return menuStore.getMenuData
    })

    // 计算菜单模式，优先使用props，否则根据布局计算
    const menuMode = computed((): 'vertical' | 'horizontal' => {
      if (props.mode) {
        return props.mode
      }
      // 竖
      const vertical: LayoutType[] = ['classic', 'topLeft', 'cutMenu']
      if (vertical.includes(unref(layout))) {
        return 'vertical'
      } else {
        return 'horizontal'
      }
    })

    // 计算是否折叠，优先使用props
    const isCollapse = computed(() => {
      if (props.collapse !== undefined) {
        return props.collapse
      }
      return appStore.getCollapse
    })

    // 计算是否只展开一个子菜单，优先使用props
    const isUniqueOpened = computed(() => {
      if (props.uniqueOpened !== undefined) {
        return props.uniqueOpened
      }
      return appStore.getUniqueOpened
    })

    // 菜单选择处理
    const menuSelect = (index: string) => {
      console.log('菜单点击事件触发，index:', index)

      // 查找对应的菜单项
      const findMenuItem = (items: MenuItem[], path: string): MenuItem | null => {
        for (const item of items) {
          if (item.path === path || item.url === path) {
            return item
          }
          if (item.children) {
            const found = findMenuItem(item.children, path)
            if (found) return found
          }
        }
        return null
      }

      const selectedItem = findMenuItem(unref(menuData), index)
      console.log('找到的菜单项:', selectedItem)

      if (selectedItem) {
        // 触发自定义事件
        emit('menu-select', selectedItem, index)

        // 如果有自定义回调，执行它
        if (props.onMenuSelect) {
          props.onMenuSelect(selectedItem, index)
        }

        // 如果有路由路径，则跳转
        if (selectedItem.path) {
          console.log('准备跳转到路径:', selectedItem.path)
          router.push(selectedItem.path)
        } else {
          console.warn('菜单项没有path属性，无法跳转:', selectedItem)
        }
      } else {
        console.warn('未找到对应的菜单项，index:', index)
      }
    }

    const renderMenuWrap = () => {
      if (unref(menuMode) === 'horizontal') {
        return renderMenu()
      } else {
        return <ElScrollbar>{renderMenu()}</ElScrollbar>
      }
    }

    const renderMenu = () => {
      const currentMenuData = unref(menuData)

      // 如果没有有效的菜单数据，返回空内容
      if (!currentMenuData || !Array.isArray(currentMenuData) || currentMenuData.length === 0) {
        console.warn('没有有效的菜单数据，跳过渲染')
        return null
      }

      return (
        <ElMenu
          defaultActive={props.activeKey}
          mode={unref(menuMode)}
          collapse={unref(menuMode) === 'horizontal' ? false : unref(isCollapse)}
          uniqueOpened={unref(menuMode) === 'horizontal' ? false : unref(isUniqueOpened)}
          backgroundColor="var(--left-menu-bg-color)"
          textColor="var(--left-menu-text-color)"
          activeTextColor="var(--left-menu-text-active-color)"
          router={true}
          popperClass={
            unref(menuMode) === 'vertical'
              ? `${prefixCls}-popper--vertical`
              : `${prefixCls}-popper--horizontal`
          }
          onSelect={menuSelect}
        >
          {{
            default: () => {
              const { renderMenuItem } = useRenderMenuItem(unref(menuMode))
              return renderMenuItem(currentMenuData)
            }
          }}
        </ElMenu>
      )
    }

    return () => (
      <div
        id={prefixCls}
        class={[
          `${prefixCls} ${prefixCls}__${unref(menuMode)}`,
          'h-[100%] overflow-hidden flex-col bg-[var(--left-menu-bg-color)]',
          {
            'w-[var(--left-menu-min-width)]': unref(isCollapse) && unref(menuMode) !== 'horizontal',
            'w-[var(--left-menu-max-width)]': !unref(isCollapse) && unref(menuMode) !== 'horizontal'
          }
        ]}
      >
        {renderMenuWrap()}
      </div>
    )
  }
})
</script>

<style lang="less" scoped>
@prefix-cls: ~'@{adminNamespace}-menu';

.@{prefix-cls} {
  position: relative;
  transition: width var(--transition-time-02);

  :deep(.@{elNamespace}-menu) {
    width: 100% !important;
    border-right: none;

    // 设置选中时子标题的颜色
    .is-active {
      & > .@{elNamespace}-sub-menu__title {
        color: var(--left-menu-text-active-color) !important;
      }
    }

    // 设置子菜单悬停的高亮和背景色
    .@{elNamespace}-sub-menu__title,
    .@{elNamespace}-menu-item {
      &:hover {
        color: var(--left-menu-text-active-color) !important;
        background-color: var(--left-menu-bg-color) !important;
      }
    }

    // 设置选中时的高亮背景和高亮颜色
    .@{elNamespace}-menu-item.is-active {
      color: var(--left-menu-text-active-color) !important;
      background-color: var(--left-menu-bg-active-color) !important;

      &:hover {
        background-color: var(--left-menu-bg-active-color) !important;
      }
    }

    .@{elNamespace}-menu-item.is-active {
      position: relative;
    }

    // 设置子菜单的背景颜色
    .@{elNamespace}-menu {
      .@{elNamespace}-sub-menu__title,
      .@{elNamespace}-menu-item:not(.is-active) {
        background-color: var(--left-menu-bg-light-color) !important;
      }
    }
  }

  // 折叠时的最小宽度
  :deep(.@{elNamespace}-menu--collapse) {
    width: var(--left-menu-min-width);

    & > .is-active,
    & > .is-active > .@{elNamespace}-sub-menu__title {
      position: relative;
      background-color: var(--left-menu-collapse-bg-active-color) !important;
    }
  }

  // 折叠动画的时候，就需要把文字给隐藏掉
  :deep(.horizontal-collapse-transition) {
    .@{prefix-cls}__title {
      display: none;
    }
  }

  // 水平菜单
  &__horizontal {
    height: calc(~'var(--top-tool-height)') !important;

    :deep(.@{elNamespace}-menu--horizontal) {
      height: calc(~'var(--top-tool-height)');
      border-bottom: none;
      // 重新设置底部高亮颜色
      & > .@{elNamespace}-sub-menu.is-active {
        .@{elNamespace}-sub-menu__title {
          border-bottom-color: var(--el-color-primary) !important;
        }
      }

      .@{elNamespace}-menu-item.is-active {
        position: relative;

        &::after {
          display: none !important;
        }
      }

      .@{prefix-cls}__title {
        /* stylelint-disable-next-line */
        max-height: calc(~'var(--top-tool-height) - 2px') !important;
        /* stylelint-disable-next-line */
        line-height: calc(~'var(--top-tool-height) - 2px');
      }
    }
  }
}
</style>

<style lang="less">
@prefix-cls: ~'@{adminNamespace}-menu-popper';

.@{prefix-cls}--vertical,
.@{prefix-cls}--horizontal {
  // 设置选中时子标题的颜色
  .is-active {
    & > .el-sub-menu__title {
      color: var(--left-menu-text-active-color) !important;
    }
  }

  // 设置子菜单悬停的高亮和背景色
  .el-sub-menu__title,
  .el-menu-item {
    &:hover {
      color: var(--left-menu-text-active-color) !important;
      background-color: var(--left-menu-bg-color) !important;
    }
  }

  // 设置选中时的高亮背景
  .el-menu-item.is-active {
    position: relative;
    background-color: var(--left-menu-bg-active-color) !important;

    &:hover {
      background-color: var(--left-menu-bg-active-color) !important;
    }
  }
}

@submenu-prefix-cls: ~'@{adminNamespace}-submenu-popper';

// 设置子菜单溢出时滚动样式
.@{submenu-prefix-cls}--vertical {
  max-height: 100%;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 6px;
    background-color: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgb(144 147 153 / 30%);
    border-radius: 4px;
  }
}
</style>
